package model;

import java.io.Serializable;
import java.util.*;

/**
 * description: 索引表
 *
 * @author wht
 * @createDate 2022/12/29 16:27
 */
public class Index implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * 记录逻辑盘块与物理盘块的对应关系 如
     * 1:13
     * 2:14
     * 3:15
     * 4:16
     */
    Map<Integer,Integer> indexMap;

    Integer size;//索引表的大小（假设一条索引占1B）

    Integer nextMap;

    public Integer getSize() {
        return size;
    }

    public void setSize(Integer size) {
        this.size = size;
    }

    public Index() {
        indexMap = new HashMap<>();
        nextMap = null;
    }


    /**
     * 获取此索引表的内存大小（一条索引占1B）
     * @return
     */
    public Integer getIndexMemorySize() {
        return indexMap.size();
    }

    public void setIndexMap(Map<Integer, Integer> indexMap) {
        this.indexMap = indexMap;
    }

    public Integer getNextMap() {
        return nextMap;
    }

    public void setNextMap(Integer nextMap) {
        this.nextMap = nextMap;
    }

    public void addIndexToMap(Integer block) {
        int size = indexMap.entrySet().size();
        int index = size+1;
        indexMap.put(index,block);
    }

    public Map<Integer,Integer> getIndexMap() {
        return this.indexMap;
    }

    /**
     * 删除最后一个
     * @return
     */
    public Integer deleteDivideBlockNum() {
        if (!indexMap.isEmpty()) {
            int size = indexMap.entrySet().size();
            Integer res = indexMap.get(size);
            indexMap.remove(size);
            return res;
        } else {
            return null;
        }
    }

    public Boolean isEmpty() {
        return indexMap.isEmpty();
    }
    /**
     * 获取分配的物理盘块数目
     * @return
     */
    public Integer getDivideBlockNum() {
        return indexMap.entrySet().size();
    }

    /**
     * 获取该索引表分配的所有物理盘块
     * @return
     */
    public String getDividedBlockString() {
        String res = "";
        Iterator<Map.Entry<Integer, Integer>> iterator = indexMap.entrySet().iterator();
        int i = 0;
        while (iterator.hasNext()) {
            res+=iterator.next().getValue()+",";
            i++;
            if (i%10==0) res+='\n';
        }
        //去掉最后的逗号，最终结果如：1,3,4,5
        return res.substring(0,res.length()-1);
    }

    public List<Integer> getDividedBlockList() {
        List<Integer> res = new LinkedList<>();
        Iterator<Map.Entry<Integer, Integer>> iterator = indexMap.entrySet().iterator();
        while (iterator.hasNext()) {
            res.add(iterator.next().getValue());
        }
        return res;
    }

    /**
     * 获取最后分配的一块磁盘，方便编辑文件内容
     * @return
     */
    public Integer getLastBlock() {
        return indexMap.get(indexMap.size());
    }

    @Override
    public String toString() {
        return "索引表";
    }
}
